﻿using FairyGUI;
using UnityEngine;
using ZFramework.Runtime;

namespace ZGame
{
    public class CustomGLoader : GLoader
    {
        private AssetLoader<Texture2D> _textureLoader;

        private int _loadingUuid;

        public CustomGLoader()
        {
            _loadingUuid = 0;
        }

        public override void Dispose()
        {
            base.Dispose();
            if (_textureLoader != null)
            {
                _textureLoader.Release();
                ReferencePool.Release(_textureLoader);
                _textureLoader = null;
            }
        }
        
        override protected void LoadExternal()
        {
            if (_textureLoader == null)
            {
                _textureLoader = AssetLoader<Texture2D>.Create(GameEntry.assetLoaderMgr, AOTGameEntry.eventMgr);
            }

            _loadingUuid = _textureLoader.LoadAssetAsync(url, (success, path, asset, userData) =>
            {
                if (!success)
                {
                    onExternalLoadFailed();
                    return;
                }

                Texture2D tex = (Texture2D) asset;
                onExternalLoadSuccess(new NTexture(tex));
            }, null);
        }

        override protected void FreeExternal(NTexture texture)
        {
            if (texture == null)
                return;
            if (_loadingUuid <= 0)
                return;
            _textureLoader.UnLoadAsset(_loadingUuid);
            _loadingUuid = 0;
        }
    }
}